<?php
/*
 * Template Name: WPSPO modèle Profil
*/

// Si on est logué mais pas participant / Admin : rien à faire ici => on le renvoi sur l'acceuil
if( !is_user_logged_in() ) {
    wp_redirect( get_option( 'siteurl').'/wp-login.php' );
    exit();
}
// On va chercher ses défis
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array( 
    'post_type'         => 'defi', 
    'posts_per_page'    => 8, 
    'post_status'       => array('publish', 'pending'),
    'author'            => $GLOBALS['current_user']->ID, 
    'paged'             => $paged,
    'orderby'           => 'post_date',
    'order'             => 'DESC'
    );
$wp_query = null;
$wp_query = new WP_Query( $args );

get_header();
?>
<script type="text/javascript">
    
    function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display === 'none') {
            e.style.display = 'block';
        } else {
            e.style.display = 'none';
        }
        
    }
    
    function calcul_total() {      

        var champP=document.getElementById("commande").elements["ChampPromesse"].value;
        var champR=document.getElementById("commande").elements["ChampRealise"].value;
        document.getElementById("commande").elements["ChampTotal"].value = parseFloat(champP) * parseFloat(champR);

    }

</script>            
<div class="content">

    <article <?php if( !empty( $rv['review'] ) ) echo $rv['review']; post_class('post-listing'); ?>>
        <div class="post-inner">
            <header class='page-header'>
                <div>
                    <div style="float:left;width:25%;"><?php echo get_wpspo_user_avatar($GLOBALS['current_user']->ID); ?></div>
                    <div style="float:left;width:75%">
                       <h1 class="name post-title entry-title entry-title"> <?php _e('Hi!', 'sponsorpress'); ?> <?php echo $GLOBALS['current_user']->display_name ?><br /><?php _e('Welcome to your personal space !', 'sponsorpress'); ?></h1><br />(<a href="/wp-admin/profile.php" style="font-size: 0.81em;"><?php _e('Edit your profil', 'sponsorpress'); ?></a>)
                    </div>
                    <div class="clear"></div>
                </div>
            </header>

            <div class="clear espace10"></div>
            <div style="margin-top:10px;margin-bottom:10px;"><?php echo (nl2br($GLOBALS['current_user']->user_desc)); ?></div>
            <?php 
            if($GLOBALS['current_user']->assodesc!="") { 
                echo "<div style=\"margin-top:10px;margin-bottom:10px;\">Représente l'association : ".$GLOBALS['current_user']->assodesc."</div>"; 

            } 
            ?>
        </div>
    </article>
    <div class="clear epsace10">&nbsp;</div>
    
    <!-- DEFIS SELON L'UTILISATEUR -->
    <article <?php if( !empty( $rv['review'] ) ) echo $rv['review']; post_class('post-listing'); ?>>
        <div class="post-inner">
            <a name="mesdefis"></a>
            <h1 class="name post-title entry-title entry-title"><?php _e('My challenges', 'sponsorpress'); ?></h1>
            <?php

            // Liste des messages d'alerte
            if($_GET['delete']==1) { echo '<div class="wpspo-erreur">'.__('Your challenge has been deleted', 'sponsorpress').'</div>'; }
            if($_GET['update']==1) { echo '<div class="wpspo-confirm">'.__('Your challenge has been changed', 'sponsorpress').'</div>'; }
            if($_GET['insert']==1) { echo '<div class="wpspo-confirm">'.__('Your challenge has been added', 'sponsorpress').'</div>'; }

            // Boucle de la requête
            if ( $wp_query->have_posts() ) : while ( $wp_query->have_posts() ) : $wp_query->the_post();

                $thePostID = $wp_query->post->ID;
                // TODO : Avant de modifier ou supprimer il faut etre sur qu'il n'y pas déjà des promesses dessus
                //Nombre de promesse sur ce défi
                $sumPromesse = WPSPO_Promesse::get_countByDefi($thePostID);

                // On va chercher les options sur ce défi
                $optionsDefi = WPSPO_Defis::get_optionsById($thePostID, $current_user->ID);
                $valueOptions = json_decode($optionsDefi->defis_option_value);

                // infos sur le projet
                $postProjet = get_post($optionsDefi->defis_id_projet);
                $permalinkProjet = get_permalink( $optionsDefi->defis_id_projet );

                 /* Compte le nombre de participants */
                $countParticipant = WPSPO_Users::get_count($thePostID);

            ?>       
                <div style="float:left;width:15%;"><small>Le <?php echo the_date('d-m-Y'); ?></small></div>
                <div style="float:left;width:60%">
                    <?php echo $phraseErreur;  ?>
                    <a href="<?php echo get_post_permalink(); ?>" onfocus="this.blur()"><strong><?php echo get_the_title(); ?></strong></a><br /><?php echo get_the_excerpt(); ?><br /><small>
                    <?php printf(_n("There is %s participant on this challenge", "There are %s participants on this challenge", $sumPromesse, 'sponsorpress'), $countParticipant); ?><br />
                    <?php printf(_n("There is %s promise on this challenge", "There are %s promises on this challenge", $sumPromesse, 'sponsorpress'), $sumPromesse); ?></small><br />
                </div>
                <div class="clear"></div>
                
                <?php 
                    if($valueOptions->cle_defis!='' && $valueOptions->share_prive==1) {
                        echo '<div id="wpspo-author-meta">';
                        printf(__('This challenge is in private mode. To participate in this challenge, your group will need a private key. Your private key is : %s', 'sponsorpress'), '<strong>'.$valueOptions->cle_defis.'</strong>');
                        echo '</div>';
                    }
                ?>
                <div style="text-align:right;">
                    
                    <div style="float:right;padding:2px;">
                        <form id="deletedefi" name="deletedefi" method="post" action="#mesdefis">
                            <?php wp_nonce_field('go-deletedefi', 'security-deletedefi'); ?>
                            <input type="hidden" name="iddefi" value="<?php echo $thePostID; ?>" />
                            <input type="submit" name="submit-deletedefi"  style="color:#ffffff;background-color:#cc0000;background: -webkit-linear-gradient(top,#cc0000 0,#cc0000 100%);border: 1px solid #cc0000;text-shadow: none;" onClick="if(!confirm('<?php _e('Are you sure you want to delete this challenge? This deletion is final, you can not retrieve this challenge.', 'sponsorpress'); ?>')) return false;" value="<?php _e('Delete', 'sponsorpress'); ?>"/>
                        </form>
                    </div>
                    <div style="float:right;padding:2px;">
                        <form id="modifydefi" name="modifydefi" method="post" action="#formdefis">
                            <?php wp_nonce_field('go-modifydefi', 'security-modifydefi'); ?>
                            <input type="hidden" name="iddefi" value="<?php echo $thePostID; ?>" />
                            <input type="hidden" name="idprojet" value="<?php echo $optionsDefi->defis_id_projet ?>" />
                            <input type="submit" name="submit-modifydefi" style="color:#ffffff;background-color:#007bc2;background: -webkit-linear-gradient(top,#007bc2 0,#007bc2 100%);border: 1px solid #007bc2;text-shadow: none;" value="<?php _e('Modify', 'sponsorpress'); ?>"/>
                        </form>
                    </div>
                </div>
                <div class="clear"></div>
                <div class="trait"></div>
            <?php 
            //}
            endwhile; 
            else :
                 _e('You have not created any challenge at the moment.', 'sponsorpress'); 
                 echo ' <a href="'.get_permalink(WPSPO_ID_ORGANISER).'"><u>'.__('Create your first challenge!', 'sponsorpress').'</u></a>';
            endif;
            ?>
        </div>
    </article>     
    <?php wpspo_theme_pagination(); ?>

    <!-- PARTICIPATION SELON L'UTILISATEUR -->
    <div class="clear epsace10">&nbsp;</div>
    <article <?php if( !empty( $rv['review'] ) ) echo $rv['review']; post_class('post-listing'); ?>>
        <div class="post-inner">
            <a name="mesparticipations"></a>
            <h1 class="name post-title entry-title entry-title"><?php _e('My participation', 'sponsorpress'); ?></h1>
            <?php
                $msgUserDelete = __('Are you sure to want to be removed from this challenge?', 'sponsorpress');
                $listParticipant = WPSPO_Users::get_listByUser($current_user->ID);
                if($listParticipant) {

                    foreach ( $listParticipant as $participant ) {

                        $leDefi = get_post($participant->users_id_defi);
                        $data = WPSPO_defis::get_options($participant->users_id_defi);
                        $valueOptions = json_decode($data->defis_option_value);
                        
                        // nb de sponsor pour chaque défi participé
                        $nbSponsor = WPSPO_Promesse::get_countParentByIdDefi($leDefi->ID, $current_user->ID);
                        if($nbSponsor>0) {
                            $listSponsor = WPSPO_Promesse::get_ParentByIdDefi($leDefi->ID, $current_user->ID);
                        }
                        //print_r($valueOptions);
                        echo '<a href="'.get_permalink($leDefi->ID).'"><strong>'.$leDefi->post_title.' ('.$valueOptions->ville_defis.')</strong></a><br />';
                        echo wpspo_display_date($valueOptions->date_defis, $valueOptions->date_end_defis).'<br />';
                        echo  __('Method of calculation donations', 'sponsorpress').' : ';
                        if($valueOptions->mode_defis==1) { 
                            printf( __('Donation Amount is %s by <b>%s</b>', 'sponsorpress'), get_wpspo_currency_symbol(), $valueOptions->text_mode_defis );
                        } else { 
                            _e('Fixed donation amount', 'sponsorpress');
                        }
                        
                        
                        $testRealiseFloat = (float)$participant->users_realise;
                        if( empty($testRealiseFloat) ) {

                            // Si le défi est par en don fixe est qu'il est termniné, on autorise de rentrer son score
                            if($valueOptions->mode_defis==1 && $post->post_status=='archive') {
                                $msgFinish = __('Do you validate that?', 'sponsorpress');
                                /* Traitement des erreurs du formulaire */
                                if (isset($_GET['erreur_r'])) {
                                    echo '<div class="clear"></div><div class="alert">';
                                        switch ($_GET['erreur_r']) {
                                            case 'zero' :
                                                echo '<script language=javascript>alert("'.__('Your result should be greater than 0', 'sponsorpress').'")</script>';
                                                break;
                                            default :
                                                echo 'Une erreur est survenue.';
                                        }
                                    echo '</div>';
                                }
                                echo "<br /><a href=\"javascript:void(0);\" onclick=\"toggle_visibility('result_".$leDefi->ID."');\" onfocus=\"this.blur()\" style=\"text-decoration:underline;\">".__('Enter your score', 'sponsorpress')."</a>";
                                echo '<div id="result_'.$leDefi->ID.'" style="display:none;margin-top:10px;background-color:#007bc2;color:#fff;padding:8px;border-radius: 5px;">';

                                /* Formulaire pour le sponsoriser */
                                echo '<form method="post" name="result_'.$leDefi->ID.'" action="#'.$leDefi->ID.$participant->users_id_user.'">';
                                echo wp_nonce_field('go-result', 'security-result');
                                echo __('I realized', 'sponsorpress').' <input type="text" size="5" name="result_num" id="result_num" value="" style="font-size: 14px;" /> '.stripslashes($valueOptions->text_mode_defis);
                                echo ' <input type="submit" onClick="if(!confirm(\''.$msgFinish.'\')) return false;" name="submit-result" value="'.__('Validate', 'sponsorpress').'" />';
                                echo '</form></div>';
                            }

                        } else {

                            echo '<div class="clear"></div>';
                            if( $_GET["realise_d"] == 1 ) {
                                echo '<div class="wpspo-confirm">'.__('Your result has been validated. Thanks!', 'sponsorpress').'</div>';
                            }
                            echo '<div><small>';
                            printf(__('Results: %s', 'sponsorpress'), wpspo_trim_zeros($participant->users_realise));
                            echo '</small></div>';
                        }
                        echo '<br /><br />';
                        if($nbSponsor>0 && $listSponsor) {
                            
                               echo '<div id="wpspo_table">
                                           <div class="wpspo_row">
                                              <span class="wpspo_cell1">';
                                                printf(_n("%s friend sponsors", "%s friends sponsors", $verifiDejaSponsor, 'sponsorpress'), $nbSponsor);
                                                echo '</span>
                                            </div>';
                                foreach($listSponsor as $sponsor) {
                                    if($valueOptions->mode_defis==1) { $txtMode = ' / '.$valueOptions->text_mode_defis; }
                                    echo '<div class="wpspo_row">
                                                  <span class="wpspo_cell">';
                                    printf( __('%s made a pledge to %s', 'sponsorpress'), get_the_author_meta( 'display_name', $sponsor->promesse_id_user ),  wpspo_price($sponsor->promesse_montant).$txtMode );
                                    
                                    /* FORMULAIRE ENTRER LES DONS */
                                    /*if( $promesse->promesse_valide==0 && $valueOptions->mode_defis==1 && $leDefi->post_status == 'archive') {
                                        
                                    if (isset($_GET['erreur_r'])) {
                                        echo '<div class="alert">';
                                            switch ($_GET['erreur_r']) {
                                                case 'zero' :
                                                    _e('Your result should be greater than 0', 'sponsorpress');
                                                    break;
                                                default :
                                                    echo 'Une erreur est survenue.';
                                            }
                                        echo '</div>';
                                    }
                                    echo " <a href=\"javascript:void(0);\" onclick=\"toggle_visibility('finish_".$sponsor->promesse_id."');\" onfocus=\"this.blur()\" style=\"text-decoration:underline;\"><small>".__('Enter his result', 'sponsorpress')."</small></a>";
                                    echo '<div id="result_'.$sponsor->promesse_id.'" style="display:none;margin-top:10px;background-color:#007bc2;color:#fff;padding:8px;border-radius: 5px;">';
                                    echo '<form method="post" name="result_'.$sponsor->promesse_id.'" id="commande" action="#mespromesses">';
                                    echo wp_nonce_field('go-result', 'security-result');
                                    echo '<input type="hidden" name="ChampPromesse" value="'.wpspo_trim_zeros($sponsor->promesse_montant).'" onkeyup="calcul_total()" >'.wpspo_price($sponsor->promesse_montant).' X <input type="text" name="ChampRealise" size="5" value=0 onkeyup="calcul_total()" >'.$valueOptions->text_mode_defis.' = <input type="text" name="ChampTotal" size="5">'.get_wpspo_currency_symbol().'';
                                    echo ' <input type="submit" onClick="if(!confirm(\''.$msgDeleteP.'\')) return false;" onfocus="this.blur()" name="submit-delpromesse" value="'.__('Submit', 'sponsorpress').'" />';
                                    echo '</form>';
                                    echo '</div>';
                                    }*/
                                    echo '</span></div>';
                                }
                            echo '</div><div class="clear espace10"></div>';
                            
                        } else if ( $leDefi->post_status!='archive' ) {
                            
                            echo '<form method="post" name="remove_participate" action="">';
                        ?><?php 
                            wp_nonce_field('go-removeme', 'security'); 
                            echo '<input type="hidden" name="defi_id" value="'.$leDefi->ID.'">
                               <input type="submit" name="submit-removeme" onClick="if(!confirm(\''.$msgUserDelete.'\')) return false;" value="'.__('Remove me from this challenge?', 'sponsorpress').'" />';
                            echo '</form><div class="clear"></div>';
                            
                        }

                        echo '<div class="clear"></div><div class="trait"></div>';
                    }
                    
                } else {
                    echo __('You have no participation for this moment.', 'sponsorpress');
                }
            ?>
        </div>
    </article>
    
    <!-- PROMESSE SELON L'UTILISATEUR -->
    <div class="clear epsace10">&nbsp;</div>
    <article <?php if( !empty( $rv['review'] ) ) echo $rv['review']; post_class('post-listing'); ?>>
        <div class="post-inner">
            <?php 
            if($_GET['validepromesse']==1) { 
                echo '<div class="wpspo-confirm">'.__('Your pledge has been validated', 'sponsorpress').'</div>'; 
            } 
            ?>
            <a name="mespromesses"></a>
            <h1 class="name post-title entry-title entry-title"><?php _e('My promises', 'sponsorpress'); ?></h1>
            <?php
            if($_GET['delete_p']==1) { 
                echo '<div class="wpspo-erreur">'.__('Your promise has been deleted', 'sponsorpress').'</div>';
            }
            if($_GET['insere_p']==1) {
                echo '<div class="wpspo-confirm">'.__('Your promise has been added', 'sponsorpress').'</div>';
            }

            /* lISTE LES PROMESSES */ 
            $ListPromesses = WPSPO_Promesse::listByUser($current_user->ID);
            if($ListPromesses) {

                foreach ( $ListPromesses as $promesse ) {
                    $defiPost = get_post($promesse->promesse_id_defi);
                    $optionsDefi2 = WPSPO_Defis::get_optionsById($promesse->promesse_id_defi, $current_user->ID);
                    $valueOptionsDefi = json_decode($optionsDefi2->defis_option_value);
                    $addTexte = '';
                    if($valueOptions->mode_defis==1) {
                        $addTexte = ' / '.$valueOptions->text_mode_defis;
                    }
                    // infos sur le projet
                    $postProjet = get_post($promesse->promesse_id_projet);
                    $msgDeleteP = __('Are you sure you want to delete this promise?\n\nThis deletion is final, you can not retrieve this promise.', 'sponsorpress');

                    printf(__('You %s sponsored the challenge %s', 'sponsorpress'), '<a href="'. get_permalink(WPSPO_ID_PARTICIPANTS).'?profil='.get_the_author_meta( 'user_nicename', $participant->users_id_user).'"><b>'.get_the_author_meta( 'display_name', $promesse->promesse_id_parent).'</b></a>', '<a href="'.get_permalink( $promesse->promesse_id_defi ).'"><b>'.$defiPost->post_title.'</b></a>' );
                    echo ' '.__('with a promise', 'sponsorpress').' '.wpspo_price($promesse->promesse_montant).$addTexte.'';
                    
                    if($valueOptionsDefi->mode_defis==1) { $addTexte = '/'.$valueOptionsDefi->text_mode_defis; }
                    echo '<div id="promesse_'.$promesse->promesse_id.'" style="margin-left:20px;color:#333;">';
                    
                    /* Si la promesse n'a pas encore été validé, il peut la supprimer */
                    if($promesse->promesse_valide==0 && $promesse->promesse_status==1) {
                                                        
                        echo '<div style="text-align:right;margin-top:10px;"><form method="post" name="promesse_user_'.$promesse->promesse_id.'" action="#mespromesses">';
                        echo wp_nonce_field('go-delpromesse', 'security-delpromesse');
                        echo '<input type="hidden" name="defi_id" value="'.$promesse->promesse_id_defi.'">';
                        echo '<input type="hidden" name="promesse_id" value="'.$promesse->promesse_id.'">';
                        echo '<input type="hidden" name="sponsor_id" value="'.$promesse->promesse_id_parent.'">';
                        echo '<input type="submit" onClick="if(!confirm(\''.$msgDeleteP.'\')) return false;" onfocus="this.blur()" name="submit-delpromesse" value="'.__('Delete', 'sponsorpress').'" />';
                        echo '</form>';
                        echo '</div>';
                        
                        
                    } else {
                        
                        echo '<div style="color:#cc0000;text-align:center">'.__('This pledge is awaiting settlement!', 'sponsorpress').'</div>';
                        
                    }
                    echo '</div>';
                    echo '<div class="clear espace15 trait"></div>';

                }
                
            } else {
                _e('You have no promise in progress.', 'sponsorpress');
            }
            ?>    
        </div>
    </article>
    
    
</div><!-- div content --> 

<?php get_sidebar(); ?>
<?php get_footer(); ?>